<template>
  <div class="hello">
    <!-- 图表容器 -->
    <div ref="chartContainer" class="chartContainer"></div>
  </div>
</template>

<script>
//引入echart折线图
import axios from "axios";
import * as echarts from "echarts/core";
import { GridComponent } from "echarts/components";
import { LineChart } from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
// import { SeriesData } from "echarts/types/dist/shared";
echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import dayjs from "dayjs";
import { KEY, API_24H } from "@/common/constrants";
import { mapActions, mapState } from "vuex";

export default {
  name: "HelloWorld",

  computed: {
    ...mapState(["location", "hour24"]),
  },
  watch:{
    location:function(){
      this.getData();
    }
  },
  created() {
    this.getData();
  },
  methods: {
    ...mapActions(["updateHour24Action"]),
    getData() {
      axios
        .get(API_24H, {
          params: {
            key: KEY,
            location: this.location.id,
            //等同于 this.$store.state.location.id
          },
        })
        .then((res) => {
          console.log(res);
          let hour24Data = {
            //临时变量，用于存放数据
            fxTime: [],
            temp: [],
          };
          // this.hourly = res.data.hourly;
          res.data.hourly.forEach((element) => {
            hour24Data.fxTime.push(element.fxTime);
            hour24Data.temp.push(element.temp);
          });
          //当24小时的数据做了变化之后，需要更新到state中
          this.updateHour24Action(hour24Data);
          //等同于 this.$store.dispatch("updateHour24Action", hour24Data);

          // let array = this.hourWeatherData.fxTime.map((data) => {
          //   return dayjs(data).format("HH");
          // });
          // let array = this.hourWeatherData.fxTime.map((data) =>
          //   dayjs(data).format("HH")
          // );
          // console.log(array);
          this.initChart(
            // this.hourWeatherData.fxTime,
            this.hour24.fxTime.map((data) => dayjs(data).format("HH")),
            this.hour24.temp
          );
        });
    },
    //设置图表
    initChart(xAxisData, seriesData) {
      var chartDom = this.$refs.chartContainer;
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        xAxis: {
          type: "category",
          // data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
          data: xAxisData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            // data: [150, 230, 224, 218, 135, 147, 260],
            data: seriesData,
            type: "line",
          },
        ],
      };

      option && myChart.setOption(option);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chartContainer {
  height: 200px;
}
</style>
